import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Notification, NotificationType } from './notification.entity';

@Injectable()
export class NotificationService {
  constructor(
    @InjectRepository(Notification)
    private notificationRepository: Repository<Notification>,
  ) {}

  async create(
    type: NotificationType,
    content: string,
    userId: number,
    relatedId?: number,
  ): Promise<Notification> {
    const notification = this.notificationRepository.create({
      type,
      content,
      userId,
      relatedId,
    });
    return this.notificationRepository.save(notification);
  }

  async findAll(userId: number, query: any): Promise<[Notification[], number]> {
    //categoryId 0 全部 1系统通知 2借阅通知 3互动通知
    const { page = 1, limit = 10, isRead,categoryId } = query;
    const skip = (page - 1) * limit;

    if (categoryId) {

    }
    const qb = this.notificationRepository
      .createQueryBuilder('notification')
      .leftJoinAndSelect('notification.user', 'user')
      .where('notification.userId = :userId', { userId });

            // 根据 categoryId 过滤通知
            if (categoryId == 1) {
              qb.andWhere('notification.type = :type', {
                type: NotificationType.SYSTEM,
              })
            }
            else if (categoryId == 2) {
              qb.andWhere('notification.type = :type', {
                type: NotificationType.BOOK_BORROWED,
              })
              .orWhere('notification.type = :type', {
                type: NotificationType.BOOK_RETURNED,
              })
              .orWhere('notification.type = :type', {
                type: NotificationType.BOOK_COMMENTED,
              })
            }
            else if (categoryId == 3) {
              qb.andWhere('notification.type = :type', {
                type: NotificationType.POST_COMMENTED,
              })
              .orWhere('notification.type = :type', {
                type: NotificationType.POST_LIKED,
              })
            }

    if (isRead !== undefined) {
      qb.andWhere('notification.isRead = :isRead', { isRead });
    }

    return qb
      .skip(skip)
      .take(limit)
      .orderBy('notification.createdAt', 'DESC')
      .getManyAndCount();
  }

  async markAsRead(id: number, userId: number): Promise<Notification | null> {
    const notification = await this.notificationRepository.findOne({
      where: { id, userId },
    });

    if (!notification) {
      return null;
    }

    notification.isRead = true;
    return this.notificationRepository.save(notification);
  }

  async markAllAsRead(userId: number): Promise<void> {
    await this.notificationRepository.update(
      { userId, isRead: false },
      { isRead: true },
    );
  }

  async getUnreadCount(userId: number): Promise<number> {
    return this.notificationRepository.count({
      where: { userId, isRead: false },
    });
  }

  async remove(id: number, userId: number): Promise<void> {
    await this.notificationRepository.delete({ id, userId });
  }
}
